package com.hurteng.stormplane.comm;

import android.util.Log;

import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommObject {
    private int command;
    private String[] args;

    public CommObject(int command, String... args) {
        this.command = command;

        this.args = new String[args.length];
        for (int i = 0; i != this.args.length; ++i) {
            this.args[i] = args[i];
        }
    }

    public CommObject() {
        this(-1, "null");
    }

    public int getCommand() {
        return command;
    }

    public void setCommand(int command) {
        this.command = command;
    }

    public Object[] getArgs() {
        return args;
    }

    public void setArgs(String... args) {
        this.args = new String[args.length];
        for (int i = 0; i != this.args.length; ++i) {
            this.args[i] = args[i];
        }
    }

    @Override
    public String toString() {
        return "CommObject{" +
                "command=" + command +
                ", args=" + Arrays.toString(args) +
                '}';
    }

    static CommObject parseCommObject(String str) {
        Pattern p = Pattern.compile("CommObject\\{.*\\}");
        Matcher m = p.matcher(str);
        if (!m.find()) {
            return new CommObject();
        }
        String objStr = m.group();
        Log.d("qinjinyu", "find: " + objStr);

        p = Pattern.compile("command=-?\\d*");
        m = p.matcher(objStr);
        if (!m.find()) {
            return new CommObject();
        }
        String cmdStr = m.group();
        Log.d("qinjinyu", "find: " + cmdStr);

        p = Pattern.compile("-?\\d*$");
        m = p.matcher(cmdStr);
        if (!m.find()) {
            return new CommObject();
        }
        int cmd = Integer.parseInt(m.group());
        Log.d("qinjinyu", "find: " + cmd);

        p = Pattern.compile("args=\\[.*\\]");
        m = p.matcher(objStr);
        if (!m.find()) {
            return new CommObject();
        }
        String argStr = m.group();
        Log.d("qinjinyu", "find: " + argStr);

        String[] res = argStr.split("(args=\\[)|(,\\s)|(\\])");
        String[] args = new String[0];
        if (res.length >= 1) {
            args = new String[res.length - 1];
            for (int i = 0; i != args.length; ++i) {
                args[i] = res[i + 1];
            }
        }
        Log.d("qinjinyu", "find: " + Arrays.toString(args));

        return new CommObject(cmd, args);
    }
}
